<template>
  <div class="page-container hide-scrollbar" ref="pageContainer">
    <div v-if="noteList.length === 0 && !isLoading" class="empty-tip">
      <p style="color: #999;">加载中...</p>
    </div>

    <div class="columns-wrapper" v-else ref="columnsWrapper">

      <div class="column column-left" ref="leftColumn">
        <div class="card" v-for="item in leftColumnCards" :key="item.id" @click="openDetails(item)">
          <div class="image">
            <img :src="item.img_url" alt="">
          </div>
          <div class="like-icon">
            <i class="one-icon one-icon-like"></i>
          </div>
          <div class="msg">
            <div class="content" v-html="item.content.replace(/\n/g, '<br>')"></div>
            <div class="user-name">{{ item.user.user_name }}</div>
            <div class="time">{{ convertDateFormat(item.input_date) }}&nbsp;·&nbsp;<span class="addr">{{ item.addr
                }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="column column-right" ref="rightColumn">
        <div class="card" v-for="item in rightColumnCards" :key="item.id" @click="openDetails(item)">
          <div class="image">
            <img :src="item.img_url" alt="">
          </div>
          <div class="like-icon">
            <i class="one-icon one-icon-like"></i>
          </div>
          <div class="msg">
            <div class="content" v-html="item.content.replace(/\n/g, '<br>')"></div>
            <div class="user-name">{{ item.user.user_name }}</div>
            <div class="time">{{ convertDateFormat(item.input_date) }}&nbsp;·&nbsp;<span class="addr">{{ item.addr
                }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多提示 -->
    <div v-if="isLoading && noteList.length > 0" class="loading-more">
      <van-loading type="spinner" color="#1989fa">加载中...</van-loading>
    </div>

    <!-- 没有更多数据提示 -->
    <div v-if="!hasMore && noteList.length > 0" class="no-more">
      <p>没有更多了</p>
    </div>

    <NoteDetail :cardData="cardDetailsData" :isVisible="showDetails" @close="closeDetails" />

  </div>
</template>

<script>
import { getNoteSquare } from '@/api/api'
import NoteDetail from '@/components/NoteDetail.vue'

export default {
  name: 'NotePage',
  components: {
    NoteDetail
  },
  data() {
    return {
      noteList: [],// 储存所有卡片数据
      cardDetailsData: {},// 储存当前卡片详情数据
      showDetails: false, // 控制详情显示
      lastDiaryId: 0, // 上一次请求最后一个元素的id，用于加载更多
      isLoading: false, // 是否正在加载，防止重复请求
      hasMore: true // 是否还有更多数据
    }
  },
  computed: {
    // 左列：奇数索引（0, 2, 4...）的卡片
    leftColumnCards() {
      return this.noteList.filter((item, index) => index % 2 === 0);
    },
    // 右列：偶数索引（1, 3, 5...）的卡片
    rightColumnCards() {
      return this.noteList.filter((item, index) => index % 2 === 1);
    }
  },
  created() {
    this.loadNoteData();
  },
  mounted() {
    // 监听滚动事件，实现滚动加载
    // 使用 nextTick 确保 DOM 已渲染
    this.$nextTick(() => {
      const container = this.$refs.pageContainer;
      if (container) {
        container.addEventListener('scroll', this.handleScroll, { passive: true });
      }
    });
  },
  beforeDestroy() {
    // 移除滚动监听
    const container = this.$refs.pageContainer;
    if (container) {
      container.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    // 加载小记数据
    loadNoteData() {
      if (this.isLoading || !this.hasMore) return;

      this.isLoading = true;
      getNoteSquare(this.lastDiaryId)
        .then(res => {
          const newList = res.data.list || [];

          if (newList.length === 0) {
            // 没有更多数据了
            this.hasMore = false;
            return;
          }
          // 将新数据添加到列表中
          this.noteList = [...this.noteList, ...newList];

          // 记录最后一个元素的id
          const lastItem = newList[newList.length - 1];
          if (lastItem && lastItem.id) {
            this.lastDiaryId = lastItem.id;
          } else {
            // 如果没有id，说明没有更多数据了
            this.hasMore = false;
          }
        })
        .catch(() => {
          console.log('加载数据失败');
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // 处理滚动事件
    handleScroll() {
      // 防止重复触发
      if (this.isLoading || !this.hasMore) return;

      const container = this.$refs.pageContainer;
      if (!container) return;

      const columnsWrapper = this.$refs.columnsWrapper;
      if (!columnsWrapper) return;

      // 获取左右两列
      const leftColumn = this.$refs.leftColumn;
      const rightColumn = this.$refs.rightColumn;

      if (!leftColumn || !rightColumn) return;

      // 计算左右两列的底部位置
      const leftColumnBottom = leftColumn.offsetTop + leftColumn.offsetHeight;
      const rightColumnBottom = rightColumn.offsetTop + rightColumn.offsetHeight;
      // 取两列中底部位置最大的那个
      const maxBottom = Math.max(leftColumnBottom, rightColumnBottom);

      // 容器的滚动高度和可视高度
      const clientHeight = container.clientHeight;
      const scrollTop = container.scrollTop;

      // 当滚动到距离底部200px以内时，加载更多
      if (maxBottom - scrollTop <= clientHeight + 200) {
        this.loadNoteData();
      }
    },

    convertDateFormat(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}.${month}.${day}`;
    },

    openDetails(item) {
      this.cardDetailsData = { ...item };
      this.showDetails = true;
    },

    closeDetails() {
      this.showDetails = false;
      this.cardDetailsData = {};
    }
  }

}
</script>

<style scoped lang="less">
.page-container {
  padding: 10vh 10px 7vh;
  box-sizing: border-box;
  background-color: #fff;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100vh;
}

.empty-tip {
  width: 100%;
  text-align: center;
  padding: 20px 0;
}

.columns-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.loading-more {
  width: 100%;
  padding: 20px 0;
  text-align: center;
  clear: both;
}

.no-more {
  width: 100%;
  padding: 20px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
  clear: both;
}

.card {
  border-radius: 8px;
  position: relative;
  box-shadow: 0 2px 4px #0000002c;
  overflow: hidden;
  width: 100%;

  .image {
    img {
      width: 100%;
      object-fit: cover;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
    }
  }

  .like-icon {
    position: absolute;
    top: 2%;
    right: 2%;
    z-index: 1;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: #00000013;

    i {
      font-size: 9px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .msg {
    padding: 10px 5px;
    line-height: 1.5;
    box-sizing: border-box;
    background-color: #fff;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    text-align: left;

    .content {
      font-size: 9px;
      margin-bottom: 10px;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.5;
    }

    .user-name,
    .time {
      font-size: 8px;
      color: #ccc;
      font-weight: 200;
    }
  }


}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>